package com.zjgeport.zjgdanger.Analysis;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.webkit.JavascriptInterface;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.Toast;

import com.github.abel533.echarts.Title;
import com.github.abel533.echarts.axis.CategoryAxis;
import com.github.abel533.echarts.axis.ValueAxis;
import com.github.abel533.echarts.code.Orient;
import com.github.abel533.echarts.code.Trigger;
import com.github.abel533.echarts.code.X;
import com.github.abel533.echarts.json.GsonOption;
import com.github.abel533.echarts.series.Line;
import com.soar.util.net.rmi.httpxml.HttpCallBack;
import com.soar.util.net.rmi.httpxml.HttpClient;
import com.soar.util.net.rmi.httpxml.HttpMethod;
import com.soar.util.net.rmi.httpxml.HttpResult;
import com.zjgeport.zjgdanger.Charts.charts.BarChart;
import com.zjgeport.zjgdanger.Charts.components.Legend;
import com.zjgeport.zjgdanger.Charts.components.XAxis;
import com.zjgeport.zjgdanger.Charts.components.YAxis;
import com.zjgeport.zjgdanger.Charts.data.BarData;
import com.zjgeport.zjgdanger.Charts.data.BarDataSet;
import com.zjgeport.zjgdanger.Charts.data.BarEntry;
import com.zjgeport.zjgdanger.Charts.data.Entry;
import com.zjgeport.zjgdanger.Charts.highlight.Highlight;
import com.zjgeport.zjgdanger.Charts.interfaces.datasets.IBarDataSet;
import com.zjgeport.zjgdanger.Charts.listener.OnChartValueSelectedListener;
import com.zjgeport.zjgdanger.Charts.utils.ColorTemplate;
import com.zjgeport.zjgdanger.CommonActivity;
import com.zjgeport.zjgdanger.LoginActivity;
import com.zjgeport.zjgdanger.R;
import com.zjgeport.zjgdanger.common.GoodsCountXAxisFormatter;
import com.zjgeport.zjgdanger.common.LogUtils;
import com.zjgeport.zjgdanger.common.MyAxisValueFormatter;
import com.zjgeport.zjgdanger.common.MyValueFormatter;
import com.zjgeport.zjgdanger.common.ParamCommon;
import com.zjgeport.zjgdanger.model.myApplication;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

public class GoodsCountTjActivity extends CommonActivity implements OnChartValueSelectedListener {

    private BarChart mChart;

    private Float AWEIGHT =0f,BWEIGHT=0f,CWEIGHT=0f;

    private List<HashMap<String, String>> data = new ArrayList<HashMap<String, String>>();

    private List<HashMap<String, String>> compList = new ArrayList<HashMap<String, String>>();

    /** Handler What加载数据完毕 **/
    private static final int WHAT_DID_LOAD_DATA = 0;

    /** Handler What更新数据完毕 **/
    private static final int WHAT_DID_REFRESH = 1;

    /** Handler What更多数据完毕 **/
    private static final int WHAT_DID_MORE = 2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_goods_count_tj);
        findTextViewById(R.id.title).setText("甲乙丙货物数量统计");
        initCommonListener();
        initData();
    }

    private void initView()
    {
        for (int i=0;i<data.size();i++){
            AWEIGHT = 0f;
            BWEIGHT = 0f;
            CWEIGHT = 0f;
            HashMap<String,String> compMap = data.get(i);
            HashMap<String,String> map = new HashMap<>();
            map.put("COMP_ABBR",compMap.get("COMP_ABBR").toString());
            for(int j=0;j<data.size();j++){
                HashMap<String,String> dataMap = data.get(j);
                if(compMap.get("COMP_ABBR").toString().equals(dataMap.get("COMP_ABBR").toString())) {
                    if (dataMap.get("ABC_TYPE").equals("1")) {
                        AWEIGHT = AWEIGHT + Float.parseFloat(dataMap.get("WEIGHT").toString());
                    } else if (dataMap.get("ABC_TYPE").equals("2")) {
                        BWEIGHT = BWEIGHT + Float.parseFloat(dataMap.get("WEIGHT").toString());
                    } else if (dataMap.get("ABC_TYPE").equals("3")) {
                        CWEIGHT = CWEIGHT + Float.parseFloat(dataMap.get("WEIGHT").toString());
                    }
                }
            }
            map.put("AWEIGHT",String.valueOf(AWEIGHT));
            map.put("BWEIGHT",String.valueOf(BWEIGHT));
            map.put("CWEIGHT",String.valueOf(CWEIGHT));
            compList.add(map);
        }

        for (int i = 0; i < compList.size() - 1; i++) {
            for (int j = compList.size() - 1; j > i; j--) {
                if (compList.get(j).equals(compList.get(i))) {
                    compList.remove(j);
                }
            }
        }

        mChart = (BarChart)findViewById(R.id.chart);
        mChart.setOnChartValueSelectedListener(this);

        mChart.getDescription().setEnabled(false);

        // if more than 60 entries are displayed in the chart, no values will be
        // drawn
        mChart.setMaxVisibleValueCount(10);

        // scaling can now only be done on x- and y-axis separately
        mChart.setPinchZoom(false);

        mChart.setDrawGridBackground(false);
        mChart.setDrawBarShadow(false);

        mChart.setDrawValueAboveBar(false);
        mChart.setHighlightFullBarEnabled(false);

        // change the position of the y-labels
        YAxis leftAxis = mChart.getAxisLeft();
        leftAxis.setValueFormatter(new MyAxisValueFormatter());
        leftAxis.setAxisMinimum(0f); // this replaces setStartAtZero(true)
        leftAxis.setSpaceBottom(0f);
        mChart.getAxisRight().setEnabled(false);

        XAxis xLabels = mChart.getXAxis();
        xLabels.setPosition(XAxis.XAxisPosition.BOTTOM);
        xLabels.setDrawGridLines(false);
        xLabels.setLabelCount(compList.size());
        xLabels.setTextSize(7f);
        xLabels.setValueFormatter(new GoodsCountXAxisFormatter(compList));

        // mChart.setDrawXLabels(false);
        // mChart.setDrawYLabels(false);

        Legend l = mChart.getLegend();
        l.setVerticalAlignment(Legend.LegendVerticalAlignment.BOTTOM);
        l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.RIGHT);
        l.setOrientation(Legend.LegendOrientation.HORIZONTAL);
        l.setDrawInside(false);
        l.setFormSize(8f);
        l.setFormToTextSpace(4f);
        l.setXEntrySpace(6f);

        setData(compList.size(),50);

    }

    /**
     * 初始化数据列表信息
     */
    private void initData() {

        HttpMethod method = new HttpMethod();
        final HashMap<String, String> map = new HashMap<String, String>();
        map.put("TOKEN", myApplication.getUser().getToken());
        method.setAction(HttpMethod.SOAR_HTTP_METHOD_ACTION_EXEC);
        method.setClassPath("com.mobile.Execute");
        method.setMethodName("getABCCOUNT");
        method.setKvdata(map);
        HttpClient.postdata(new Button(GoodsCountTjActivity.this), method, ParamCommon.ptl_server_url, true, new HttpCallBack() {
            @Override
            public void run(HttpResult result) {
                if (result.getResultCode().equals(HttpResult.SOAR_HTTP_STATUS_CODE_SUCCESS)) {
                    List<HashMap<String, String>> data1 = result.getDataSet();
                    if (data1 != null && data1.size() != 0) {
                        data.addAll(data1);
                    }

                } else {
                    Toast.makeText(getApplication(),result.getResultMessage(),1).show();
                    if (result.getResultCode().equals("90"))
                    {
                        Intent intent = new Intent(GoodsCountTjActivity.this,LoginActivity.class);
                        startActivity(intent);
                    }
                }

                // 刷新UI
                Looper mainLooper = Looper.getMainLooper();
                MyHandler handler = new MyHandler(mainLooper);
                Message msg = new Message();
                msg.what = WHAT_DID_LOAD_DATA;
                msg.obj = data;
                handler.sendMessage(msg);

            }
        });
    }

    private class MyHandler extends Handler
    {
        public MyHandler(Looper looper)
        {
            super(looper);
        }

        @SuppressWarnings("unchecked")
        public void handleMessage(Message msg)
        {
            switch (msg.what)
            {
                case WHAT_DID_LOAD_DATA:
                    initView();
                    break;
                default:
                    break;
            }
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.bar, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        switch (item.getItemId()) {
            case R.id.actionToggleValues: {
                List<IBarDataSet> sets = mChart.getData()
                        .getDataSets();

                for (IBarDataSet iSet : sets) {

                    BarDataSet set = (BarDataSet) iSet;
                    set.setDrawValues(!set.isDrawValuesEnabled());
                }

                mChart.invalidate();
                break;
            }
            case R.id.actionToggleIcons: {
                List<IBarDataSet> sets = mChart.getData()
                        .getDataSets();

                for (IBarDataSet iSet : sets) {

                    BarDataSet set = (BarDataSet) iSet;
                    set.setDrawIcons(!set.isDrawIconsEnabled());
                }

                mChart.invalidate();
                break;
            }
            case R.id.actionToggleHighlight: {
                if (mChart.getData() != null) {
                    mChart.getData().setHighlightEnabled(!mChart.getData().isHighlightEnabled());
                    mChart.invalidate();
                }
                break;
            }
            case R.id.actionTogglePinch: {
                if (mChart.isPinchZoomEnabled())
                    mChart.setPinchZoom(false);
                else
                    mChart.setPinchZoom(true);

                mChart.invalidate();
                break;
            }
            case R.id.actionToggleAutoScaleMinMax: {
                mChart.setAutoScaleMinMaxEnabled(!mChart.isAutoScaleMinMaxEnabled());
                mChart.notifyDataSetChanged();
                break;
            }
            case R.id.actionToggleBarBorders: {
                for (IBarDataSet set : mChart.getData().getDataSets())
                    ((BarDataSet) set).setBarBorderWidth(set.getBarBorderWidth() == 1.f ? 0.f : 1.f);

                mChart.invalidate();
                break;
            }
            case R.id.animateX: {
                mChart.animateX(3000);
                break;
            }
            case R.id.animateY: {
                mChart.animateY(3000);
                break;
            }
            case R.id.animateXY: {

                mChart.animateXY(3000, 3000);
                break;
            }
            case R.id.actionSave: {
                if (mChart.saveToGallery("title" + System.currentTimeMillis(), 50)) {
                    Toast.makeText(getApplicationContext(), "Saving SUCCESSFUL!", Toast.LENGTH_SHORT).show();
                } else
                    Toast.makeText(getApplicationContext(), "Saving FAILED!", Toast.LENGTH_SHORT).show();
                break;
            }
        }
        return true;
    }

    private void setData(int count, float range) {

        ArrayList<BarEntry> yVals1 = new ArrayList<BarEntry>();

        for (int i = 0; i < compList.size(); i++) {
            HashMap<String, String> dataMap = compList.get(i);
            Float valueA = Float.parseFloat(dataMap.get("AWEIGHT").toString());
            Float valueB = Float.parseFloat(dataMap.get("BWEIGHT").toString());
            Float valueC = Float.parseFloat(dataMap.get("CWEIGHT").toString());


            yVals1.add(new BarEntry(
                    i,
                    new float[]{valueA, valueB, valueC},
                    getResources().getDrawable(R.drawable.star)));
        }

        BarDataSet set1;

        if (mChart.getData() != null &&
                mChart.getData().getDataSetCount() > 0) {
            set1 = (BarDataSet) mChart.getData().getDataSetByIndex(0);
            set1.setValues(yVals1);
            mChart.getData().notifyDataChanged();
            mChart.notifyDataSetChanged();
        } else {
            set1 = new BarDataSet(yVals1, "");
            set1.setDrawIcons(false);
            set1.setColors(getColors());
            set1.setStackLabels(new String[]{"甲类", "乙类", "丙类"});

            ArrayList<IBarDataSet> dataSets = new ArrayList<IBarDataSet>();
            dataSets.add(set1);

            BarData data = new BarData(dataSets);
            data.setValueFormatter(new MyValueFormatter());
            data.setValueTextColor(Color.WHITE);
            data.setValueTextSize(7f);

            mChart.setData(data);
        }

        mChart.setFitBars(true);
        mChart.invalidate();
    }



    @Override
    public void onValueSelected(Entry e, Highlight h) {

        BarEntry entry = (BarEntry) e;

        if (entry.getYVals() != null)
            Log.i("VAL SELECTED", "Value: " + entry.getYVals()[h.getStackIndex()]);
        else
            Log.i("VAL SELECTED", "Value: " + entry.getY());
    }

    @Override
    public void onNothingSelected() {
        // TODO Auto-generated method stub

    }

    private int[] getColors() {

        int stacksize = 3;

        // have as many colors as stack-values per entry
        int[] colors = new int[stacksize];

        for (int i = 0; i < colors.length; i++) {
            colors[i] = ColorTemplate.MATERIAL_COLORS[i];
        }

        return colors;
    }

}
